package cn.jiyun.user.service.impl;

import cn.jiyun.user.mapper.UserMapper;
import cn.jiyun.user.pojo.User;
import cn.jiyun.user.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /*@Autowired
    private RedisTemplate<String,String> redisTemplate;*/

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<User> findAll() {
        String userListStr = redisTemplate.boundValueOps("userList").get();
        ObjectMapper objectMapper = new ObjectMapper();
        List<User> userList = null;
        if(StringUtils.isEmpty(userListStr)){
            //缓存中没有数据，那就查询数据库
            //select * from tb_user
            userList = userMapper.selectList(null);
            try {
                //将查询结果存入缓存中
                String str = objectMapper.writeValueAsString(userList);
                redisTemplate.boundValueOps("userList").set(str);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            System.out.println("从数据库中查询数据");
        }else{
            try {
                userList =  objectMapper.readValue(userListStr,List.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("从Redis中查询数据");
        }


        return userList;
    }
}
